#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === Android Image Extractor ===
function androidextractimage()
{
  # Usage
  if [ -z "${1}" ] || [ ! -f "${1}" ] || [ -z "${2}" ]; then
    echo '';
    echo ' Usage: androidextractimage <file.img> <output_path> (Android filesystem.img extractor)';
    echo '';
    return;
  fi;

  # Variables
  local file_img=${1};
  local output_path=${2};
  local temp_dir;
  local temp_img;

  # Prepare input, output and temp paths
  mkdir -p "${output_path}";
  file_img=$(readlink -f "${file_img}");
  temp_dir=$(mktemp -d);
  temp_img=$(mktemp);

  # Access temp path
  cwd=$(pwd);
  cd "${output_path}/";
  echo '';

  # Mount image as to temporary folder
  simg2img "${file_img}" "${temp_img}";
  sudo mount -t ext4 -o loop "${temp_img}" "${temp_dir}/";
  sudo chown -R "$(whoami):$(whoami)" "${temp_dir}/";

  # Import all mounted files to output
  cp -rfv "${temp_dir}/." './';

  # Delete temporary paths
  sudo umount "${temp_dir}";
  rm -rf "${temp_dir}";
  rm -f "${temp_img}";

  # Restore path
  cd "${cwd}/";
  echo '';
}
